<?php
/**
 * 订单
 */
class IndentHelper {
	
	public static function getList($where=null, $s=0, $l=0){
                $from = fetch_a_string('from') ? fetch_a_string('from').' 00:00:00' : '';
		$to   = fetch_a_string('to') ? fetch_a_string('to').' 23:59:59' : '';
		if($from)  $where .= ' AND `t0`.`addtime`>='.strtotime($from);
		if($to)	 $where .= ' AND `t0`.`addtime`<='.strtotime($to);
            
		return Db::get('Indent')->select('t0.*,t1.name as supplier_name,t2.name as user_name')
				->where($where)
				->join(array('Supplier', 'User'))->on(array('t0.supplier_id=t1.id','t0.user_id=t2.id'))
				->order('id DESC')->limit($s,$l)->hkey('id')->getAll();
	}

	public static function count($where=null){
                $from = fetch_a_string('from') ? fetch_a_string('from').' 00:00:00' : '';
		$to   = fetch_a_string('to') ? fetch_a_string('to').' 23:59:59' : '';
		if($from)  $where .= ' AND `addtime`>='.strtotime($from);
		if($to)	 $where .= ' AND `addtime`<='.strtotime($to);
		return Db::get('Indent')->count()->where($where)->getCol();
	}

	public static function audit2txt($indent_audit_flow){
		static $sets = array(0=>'待审', 1=>'通过', 2=>'失败');
		return fetch_a_char($indent_audit_flow, $sets);
	}

	public static function back2txt($indent_back_flow){
		static $sets = array(0=>'无入库', 1=>'有入库', 2=>'入库完');
		return fetch_a_char($indent_back_flow, $sets);
	}

	/**
	 * 查看采购订单的详细信息
	 */
	static function getDetail($indent_id){
		$indent = Indent::getDetail($indent_id);
		if(!$indent){
			return false;
		}
		$indent['items'] = IndentItems::getByIndent($indent_id);
		return $indent;
	}

	/**
	 * 检查查看权限
	 */
	static function hasPurview($indent_id){
		//todo: 查看采购订单，需要权限验证吗？哪些人可见？采购部？制单人同部门人？
		return true;
	}
	
	/**
	 * 强制结采购单
	 * 
	 * 有两种情况：
	 *  A 更换供应商，重走录入报价流程
	 *    对于更改供应商，改变原订单的供应商，材料价格，若已有材料入库，使用新编号，否则订单编号不变。
	 *    更改供应商，订单是按供应商生成的，若订单已有部分入库，此时不能更改供应商，应做强制结单处理。
	 * 
	 *  B 规格有变化的重走采购需求
	 *    1 不用通知采购需求的满足情况（系统外执行）；
	 *    2 对于订单已有部分材料入库的订单，标记为订单已完成；实际回库数量可能比订单数小；
	 *    清除demand.summary_id，
	 * 
	 * 
	 * 有部分材料入库时做强制结单，重走采购需求流程。
	 * 
	 * @param int $type 1:强制结单 2:改变供应商
	 */
	static function forceStop($indent_id, $type, &$errmsg=''){
		$indent = Indent::get($indent_id);
		if(!$indent){
			$errmsg = '无此采购订单记录';
			return false;
		}
		
		//检查是否可结单的订单
		if($indent['audit_flow']!=1){
			$errmsg = '采购订单未通过审核';
			return false;
		}
		if($indent['back_flow']==2){
			$errmsg = '采购订单已完成入库';
			return false;
		}
		
		//强制结单，且有入库的，要求选择“强制结单”
		if($type==2 && $indent['back_flow']!=0){
			$errmsg = '此订单已有入库记录，请尝试使用“强制结单”';
			return false;
		}
		
		$indentitems = IndentItems::getByIndent($indent_id);
		
		/*
		 * 改变供应商
		 */
		if($type==2){
			Db::get()->trans()->on();
			/*
			 * 标记订单为 完成入库，这样订单在入库界面将不能再操作；
			 * 标记订单材料为已完成入库；
			 * 标记采购汇总表为 未报价且待生成订单；
			 */
			if(Indent::update($indent_id, array('back_flow'=>2))){
				//修改订单材料为 完成采购
				$r1 = Db::get('IndentItems')->update(array('off'=>1))->where(array(
						'indent_id' => $indent_id,
					))->exec();
				//修改采购汇总表状态为 待生成订单&未报价
				$r2 = Summary::update($indent['summary_id'], array(
								'flow' => 0, 
								'quote_flow' => 0,
							));
				if(!$r1 || !$r2) {
					$errmsg = '修改原始采购汇总记录出错';
					Db::get()->trans()->rollback();
					return false;
				}
				//todo:  修改 demand_items.state/supplier_id
//				$wareids = Db::get('_demand_items')->select('ware_id')->where(array(
//								'demand_id'		=> $demand_id,
//								'supplier_id'	=> '',
//								'summary_id'	=> '',
//							))->getCols();
//				Db::get('DemandItems')->update(array('state'=>1,'supplier_id'=>NULL))
//						->where(array('demand_id'=>$demand_id),array('ware_id','IN',$wareids))->exec();
			}
			else{
				$errmsg = '修改订单状态失败';
				Db::get()->trans()->rollback();
				return false;
			}
		}
		/*
		 * 强制结单
		 */
		else{
			$errmsg = '数据有误';
			Db::get()->trans()->rollback();
			
			return false;
		}
		
		Db::get()->trans()->commit();
		return true;
	}

	/**
	 * 取采购订单需求方人员列表
	 */
	static function getDemandPeople($indent_id){
		return self::hkey(
			Db::get('Indent')->select('t2.name,t1.user_id')
				->join(array('Demand','User'))->on(array('t0.summary_id=t1.summary_id','t1.user_id=t2.id'))
				->where("t0.id={$indent_id}")
				->group('t1.user_id')->getAll() );
	}
	
	static function getIndentPeople($indent_id){
		return self::hkey(
			Db::get('Indent')->select('t1.name,t0.user_id')
				->join(array('User'))->on(array('t0.user_id=t1.id'))
				->where("t0.id={$indent_id}")
				->group('t0.user_id')->getAll() );
	}
	
	private static function hkey($array2d){
		if($array2d){
			$tmp = array();
			foreach($array2d as $row){
				$tmp[$row['user_id']] = $row['name'];
			}
			return $tmp;
		}
		return array();
	}
	
	/**
	 * 采购明细汇总；因订单表不可能记录部门、采购类型，所以记录出自采购需求表state=3的记录 
	 */
	static function getDetailSummary($month=''){
		$month = $month ? intval($month) : date('Ym');
                $where = "state=".DemandItems::STATE_INDENT." AND sum_month={$month}";
                $dept = fetch_a_int('dept');
                if($dept)
                {
                    $where .=" AND `dept_id`={$dept}";
                }                
                $where .= ' AND '. Lib::makeTimesRange();
                

		$items = Db::get('_DemandItems')->select('*,price*amount AS total')
					->where($where)
					->order('sno ASC,demand_type ASC')->getAll();
		/**
		 * todo: 如下内容显示时只对部门做了水平切分，供应商显示可能有误；
		 */
		$tmp = array();
		foreach($items as $item){
			if(!isset($tmp[$item['ware_id']])){
				$tmp[$item['ware_id']] = array_intersect_key($item, array_flip(array(
					'ware_id','class_id','class_path','sno','name','brand','specific','unit',
					'price', 'quote_time', )));
				$tmp[$item['ware_id']]['amount'] = 0;
				$tmp[$item['ware_id']]['total'] = 0;
				$tmp[$item['ware_id']]['list'] = array();
			}
			$list =& $tmp[$item['ware_id']]['list'];
			if(!isset($list[$item['dept_id']])){
				$list[$item['dept_id']] = array(
					'name'	=> $item['dept_name'],
					'supplier_id'	=> $item['supplier_id'],
					'supplier_name'	=> $item['supplier_name'],
					);
			}
			$list[$item['dept_id']][$item['demand_type']] = array_intersect_key($item,
					array_flip( array('amount', 'demand_type', 'dept_id', 'sum_month', 'dept_name') ));
			$tmp[$item['ware_id']]['amount'] += $item['amount'];
			$tmp[$item['ware_id']]['total'] += $item['total'];
			unset($list);
		}
		return $tmp;
	}
	
	/**
	 * 月采购汇总
	 */
	static function getMonthSummary($month=''){
		$month = $month ? intval($month):date('Ym');
                
                $month = substr($month,0,4).'-'.substr($month,4,2);
                $lastdate = strtotime(date("Y-m-1",strtotime($month)));
                $nextdate = strtotime(date("Y-m-1",strtotime("next month",strtotime($month))));
                
                $where = "addtime>={$lastdate} AND addtime<{$nextdate}";
                //如果选定日期则忽略月份参数
                if(Lib::makeTimesRange()!=1)
                {
                    $where = Lib::makeTimesRange();
                }        
                
                //var_dump($month,date("Y-m-12",strtotime("last month",strtotime($month))),date("Y-m-12",strtotime($month))) & die;
                //取出质检最后一位的日期在些范围内的所有related_id
                
                //再根据得出的related_id 对应 `bound_items` 的 bound_id，找出indent_id
                $indent_id_arr = Db::get('bound')
					->select('`indent_id`')
					->where('id in(SELECT `related_id` FROM `_reviewer` WHERE `class`=3 AND `pass`=1 AND '.$where.' GROUP BY `related_id` ORDER BY `addtime` DESC)')
					->group('`indent_id`')->getCols();
                
                if(!$indent_id_arr)
                {
                    return array(array(), array(), array());
                }
                //再根据indent_id找出订单号
                $sno_arr = Db::get('indent')->select('`pr_no`')->where('id in('.implode(',', $indent_id_arr).')')->getCols();
                if(!$sno_arr)
                {
                    return array(array(), array(), array());
                }
                $sno_arr = array_unique(explode(',',implode(',', $sno_arr)));
                
                //再根据订单号找出 _demand_items表的demand_id
                $_str ="'".implode("','",$sno_arr)."'";
                $demand_id_arr = Db::get('demand')->select('`id`')->where("`sno` in(".$_str.")")->group('`id`')->getCols();
              
                if(!$demand_id_arr)
                {
                    return array(array(), array(), array());
                }
                //var_dump($demand_id_arr) & die;
                
                //最后找出_DemandItems表里数据
                $where = 'demand_id in ('.implode(',', $demand_id_arr).')';
                
              // var_dump($where);
//		echo $month, '<br/>';
		$tmp   = Db::get('_DemandItems')
					->select('sum(amount_back*price) AS total,supplier_id,supplier_name,demand_type,dept_id,dept_name')
					->where($where)
					->group('supplier_id,dept_id,demand_type')->getAll();
                
                
		$types = array();
		$list  = array();
		$depts = array();
		foreach($tmp as $row){
			if(!isset($list[$row['supplier_id']])){
				$list[$row['supplier_id']] = array(
					'supplier_id' => $row['supplier_id'],
					'supplier_name' => $row['supplier_name'],
					'total' => 0.0,
					'types' => array(),
				);
			}
			if(empty($list[$row['supplier_id']]['types'][$row['demand_type']])){
				$list[$row['supplier_id']]['types'][$row['demand_type']] = array(
					'total' => 0.0,
					'depts' => array(),
				);
			}
			$list[$row['supplier_id']]['types'][$row['demand_type']]['depts'][$row['dept_id']] = array(
				'dept_name' => $row['dept_name'],
				'total'		=> $row['total'],
			);
			$list[$row['supplier_id']]['total'] += $row['total'];
			$list[$row['supplier_id']]['types'][$row['demand_type']]['total'] += $row['total'];
			if(!isset($types[$row['demand_type']])){
				$types[$row['demand_type']] = 0.0;
			}
			$types[$row['demand_type']] += $row['total'];
			//为排除不使用的部门
			$depts[] = $row['dept_id'];
		}
//		Debug::pre($list);
//		Debug::pre($types);
		return array($list, $types, array_unique($depts));
	}
	
	static function getYearSummary($year){
		$year_cond = "(sum_month>{$year}00 AND sum_month<{$year}13 AND state=".DemandItems::STATE_INDENT.")";
		return array(
			'dept'	=> self::getDeptYearSummary($year_cond),
			'supplier' => self::getSupplierYearSummary($year_cond),
			'type'	=> self::getTypeYearSummary($year_cond),
		);
	}
	
	static function getDeptYearSummary($year_cond){
		$tmp = Db::get('_DemandItems')
				->select('SUM(amount_back*price) AS total,sum_month,dept_id,dept_name')
				->where($year_cond)
				->group('sum_month,dept_id')->getAll();
		$list = array();
		foreach($tmp as $t){
			if(!isset($list[$t['dept_id']])){
				$list[$t['dept_id']] = array('name'=>$t['dept_name'], 'month'=>array(), 'total'=>0.0);
			}
			$list[$t['dept_id']]['month'][ intval(substr($t['sum_month'],4)) ] = $t['total'];
			$list[$t['dept_id']]['total'] += $t['total'];
		}
//		Debug::pre($list);
		return $list;
	}
	
	static function getSupplierYearSummary($year_cond){
		$tmp = Db::get('_DemandItems')
				->select('SUM(amount_back*price) AS total,sum_month,supplier_id,supplier_name')
				->where($year_cond)
				->group('sum_month,supplier_id')->getAll();
		$list = array();
		foreach($tmp as $t){
			if(!isset($list[$t['supplier_id']])){
				$list[$t['supplier_id']] = array('name'=>$t['supplier_name'], 'month'=>array(), 'total'=>0.0);
			}
			$list[$t['supplier_id']]['month'][ intval(substr($t['sum_month'],4)) ] = $t['total'];
			$list[$t['supplier_id']]['total'] += $t['total'];
		}
//		Debug::pre($list);
		return $list;
	}
	
	static function getTypeYearSummary($year_cond){
		$tmp = Db::get('_DemandItems')
				->select('SUM(amount_back*price) AS total,sum_month,demand_type')
				->where($year_cond)
				->group('sum_month,demand_type')->getAll();
		$list = array();
		foreach($tmp as $t){
			if(!isset($list[$t['demand_type']])){
				$list[$t['demand_type']] = array('month'=>array(), 'total'=>0.0);
			}
			$list[$t['demand_type']]['month'][ intval(substr($t['sum_month'],4)) ] = $t['total'];
			$list[$t['demand_type']]['total'] += $t['total'];
		}
//		Debug::pre($list);
		return $list;
	}
	
}
?>
